package com.lw.leetcode.linked.b;

import com.lw.leetcode.linked.ListNode;

/**
 * 剑指 Offer II 021. 删除链表的倒数第 n 个结点
 * 19. 删除链表的倒数第 N 个结点
 *
 * @Author liw
 * @Date 2021/9/5 14:34
 * @Version 1.0
 */
public class RemoveNthFromEnd {
    public ListNode removeNthFromEnd(ListNode head, int n) {

        ListNode l1 = head;
        ListNode l2 = null;
        while (n > 0) {
            l1 = l1.next;
            n--;
        }
        while (l1 != null) {
            if (l2 == null) {
                l2 = head;
            } else {
                l2 = l2.next;
            }
            l1 = l1.next;
        }

        if (l2 == null) {
            return head.next;
        }
        l2.next = l2.next.next;
        return head;
    }
}
